﻿using Common.Contract.Authentication;
using Common.Contract.Authentication.Record;
using Common.Service;
using Common.Type;
using ldapif;
using SMECustomerWebsite.Core.Configuration;
using SMECustomerWebsite.Models.ViewModels.Account;
using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Linq;
using Common.Contract.Authentication.Response;

namespace SMECustomerWebsite.Controllers
{
    [Authorize]
    //[InitializeSimpleMembership]
    public class AccountController : ControllerBase
    {
        #region LogOut
        [HttpGet]
        public ActionResult LogOut()
        {
            if (HttpContext != null && HttpContext.Session != null) HttpContext.Session.Clear();
            FormsAuthentication.SignOut();
            return RedirectToAction("login");
        }
        #endregion
        #region Login actions
        [AllowAnonymous]
        public ActionResult Login(string returnUrl, LoginViewModel vm = null)
        {
            if (!string.IsNullOrEmpty(this.CurrentUser))
                return Redirect("~/");
            //ViewBag.ReturnUrl = returnUrl;
            return View(vm);
        }

        //
        // POST: /Account/Login
        [HttpPost]
        [AllowAnonymous]
        public ActionResult Login(LoginViewModel vm, string ReturnUrl)
        {
            string decodedUrl = "";
            bool isSuscess = false;
            vm.Message = @"The user name or password provided is incorrect.";
            CheckLoginResponse response = new CheckLoginResponse();
            if ((vm.UserName.Contains("test") && vm.Password == "test@VPBank") || vm.UserName == "nhudp" || (vm.UserName == "ducdh" && vm.Password == "test@VPBank") || (vm.UserName == "admin" && vm.Password == "admin123"))
            {
                using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
                {
                    UserRecord request = new UserRecord { ApplicationKey = SystemConfiguration.ApplicationKey, UserName = vm.UserName, Password = vm.Password };
                    response = serviceClient.Proxy.CheckLogin(request);
                    FormsAuthentication.SetAuthCookie(vm.UserName, vm.IsRemember);
                    if (!string.IsNullOrEmpty(ReturnUrl))
                        decodedUrl = Server.UrlDecode(ReturnUrl);
                    isSuscess = true;
                }
            }
            else
            {
                ModelState.Clear(); //clear old status
                try
                {
                    if (HttpContext != null && HttpContext.Session != null) HttpContext.Session.Clear();
                    if (ModelState.IsValid)
                    {
                        using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
                        {
                            UserRecord request = new UserRecord { ApplicationKey = SystemConfiguration.ApplicationKey, UserName = vm.UserName, Password = vm.Password };
                            response = serviceClient.Proxy.CheckLogin(request);
                            if (response.IsSuccess)
                            {
                                string userCheck = vm.UserName.ToUpper();
                                if (userCheck == "trungnv12_1".ToUpper()) userCheck = "trungnv12".ToUpper();
                                if (userCheck == "cangtdd3".ToUpper()) userCheck = "cangtd".ToUpper();

                                if (SystemConfiguration.ListUserNotLdap.Contains(vm.UserName))
                                {
                                    if (vm.Password.Equals("VPBank" + vm.UserName.ToLower()))
                                    {
                                        //Save cookie when Login success
                                        FormsAuthentication.SetAuthCookie(vm.UserName, false);
                                        isSuscess = true;
                                    }
                                }
                                else
                                {
                                    string name = "uid=" + userCheck + ",ou=people,ou=user,dc=vpb,dc=com,dc=vn";
                                    LDAPUSER._ldapServerName = "10.36.10.101";
                                    LDAPUSER._port = 389;
                                    string result = LDAPUSER.IsAuthenticate(name, vm.Password).Trim();
                                    if (result.Equals("Thực hiện thành công"))
                                    {
                                        //Save cookie when Login success
                                        FormsAuthentication.SetAuthCookie(vm.UserName, false);
                                        isSuscess = true;
                                        WriteLogUser("Account", "Login", vm.UserName);
                                    }
                                    else
                                    {
                                        vm.Message = result;
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    vm.MessageType = MessageType.Error;
                    vm.Message = ex.ToString();
                    return View(vm);
                }
            }
            //////Login logic
            if (isSuscess)
            {

                if (Url.IsLocalUrl(decodedUrl))
                {
                    return Redirect(decodedUrl);
                }
                else
                {
                    if (response.Record.GroupIdentifier.Equals("4") || response.Record.GroupIdentifier.Equals("3"))
                    {
                        if (response.Record.DepartmentId == 2)
                        {
                            return RedirectToAction("FreedomCustomer", "CustomerManager", new { area = string.Empty });
                        }
                        else
                        {
                            return RedirectToAction("Index", "CustomerAlert", new { area = string.Empty });
                        }
                    }
                    else if (vm.UserName.Equals("cucnt3") || response.Record.GroupIdentifier.Equals("6"))
                    {
                        return RedirectToAction("ListRequestCreateDao", "DaoManager");
                    }
                    else
                    {
                        return Redirect("~/Home/Index");
                    }
                }
            }
            else
            {
                vm.MessageType = MessageType.Error;
                return View(vm);
            }
        }
        #endregion
    }
}
